package com.lingyun.common.utils.quartz;

import com.lingyun.common.constant.ScheduleConstants;
import com.lingyun.common.pojo.LyJob;
import com.lingyun.common.utils.bean.BeanUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;

/**
 * 抽象quartz调用
 *
 * @author
 */
public abstract class AbstractQuartzJob implements Job {
    private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class);

    /**
     * 线程本地变量
     */
    private static ThreadLocal<Date> threadLocal = new ThreadLocal<>();

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        LyJob job = new LyJob();
        BeanUtils.copyBeanProp(job, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES));
        try {
            before(context, job);
            if (job != null) {
                doExecute(context, job);
            }
            after(context, job, null);
        } catch (Exception e) {
            log.error("任务执行异常  - ：", e);
            after(context, job, e);
        }
    }

    /**
     * 执行前
     *
     * @param context 工作执行上下文对象
     * @param job  系统计划任务
     */
    protected void before(JobExecutionContext context, LyJob job) {
        threadLocal.set(new Date());
    }

    /**
     * 执行后
     *
     * @param context 工作执行上下文对象
     * @param job  系统计划任务
     */
    protected void after(JobExecutionContext context, LyJob job, Exception e) {
        Date startTime = threadLocal.get();
        threadLocal.remove();

// 这里是执行后写日志，以后如果要写，才能考若依，现在以能跑起来为主
//        final SysJobLog sysJobLog = new SysJobLog();
//        sysJobLog.setJobName(job.getJobName());
//        sysJobLog.setJobGroup(job.getJobGroup());
//        sysJobLog.setInvokeTarget(job.getInvokeTarget());
//        sysJobLog.setStartTime(startTime);
//        sysJobLog.setStopTime(new Date());
//        long runMs = sysJobLog.getStopTime().getTime() - sysJobLog.getStartTime().getTime();
//        sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时：" + runMs + "毫秒");
//        if (e != null) {
//            sysJobLog.setStatus(Constants.FAIL);
//            String errorMsg = StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000);
//            sysJobLog.setExceptionInfo(errorMsg);
//        } else {
//            sysJobLog.setStatus(Constants.SUCCESS);
//        }
//        // 写入数据库当中
//        SpringUtils.getBean(ISysJobLogService.class).addJobLog(sysJobLog);
    }

    /**
     * 执行方法，由子类重载
     *
     * @param context 工作执行上下文对象
     * @param job  系统计划任务
     * @throws Exception 执行过程中的异常
     */
    protected abstract void doExecute(JobExecutionContext context, LyJob job) throws Exception;
}
